package com.itheima.reggie.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.R;
import com.itheima.reggie.common.util.ValidateCodeUtils;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.mapper.UserMapper;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.sql.Struct;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;




    //用户登出
    @Override
    public R userLoginOut(HttpSession session) {
        session.removeAttribute("userId");
        return R.success("退出成功");
    }
    //短信验证登录
    @Override
    public R userLogin(Map<String, String> map, HttpSession session) {
        //获取用户电话
        String phone = map.get("phone");
        //获取用户给的验证码
        String code = map.get("code");
        if (StrUtil.hasEmpty(phone)) {
            return R.error("电话不能为空");
        } else if (StrUtil.hasEmpty(code)) {
            return R.error("验证码不能为空");
        }
        //从session获取真正的验证码
        String sessionCode = (String) session.getAttribute(phone);
        if (!sessionCode.equals(code)) {
            return R.error("验证码错误");
        }
        //根据电话查询用户数据
        User user = userMapper.getUserByPhone(phone);
        //判断是否是新用户
        if (user == null) {
          //新用户,创建用户信息
            user = new User();
            user.setStatus(1);
            user.setPhone(phone);
            userMapper.insert(user);
        }
        //将验证码清除
        session.removeAttribute(phone);
        //将用户id存入session
        session.setAttribute("userId",user.getId());
        return R.success("登录成功");
    }




    //发送短信
    @Override
    public R sendMsg(User user, HttpSession session) {
        //String code4String = ValidateCodeUtils.generateValidateCode4String(6);
        String phone = user.getPhone();
        if (StrUtil.hasEmpty(phone)){
            return R.success("电话不能为空");
        }
        String code4String = RandomUtil.randomNumbers(6);
        //System.out.println(code4String);
        log.info("当前验证码为：" +code4String);
        session.setAttribute(phone, code4String);
        return R.success("验证码发送成功");
    }


}
